package com.xnyzc.lhy.didi.service.impl.other;

import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.component.didi.DiDiUrlConstant;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.retry.RetryUtil;
import com.xnyzc.lhy.common.util.sign.AttestationTool;
import com.xnyzc.lhy.didi.entity.param.other.BindCouponParam;
import com.xnyzc.lhy.didi.service.other.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 优惠券相关
 *
 * @author zhengxu
 */
@Service
@Slf4j
public class CouponServiceImpl implements CouponService {
    @Override
    public DiDiRv bindByUidBack(BindCouponParam couponParam) {
        if (CheckUtil.strIsEmpty(couponParam.getPassenger_phone()) || CheckUtil.strIsEmpty(couponParam.getCoupon_amount())) {
            throw DiDiException.create(EDiDiErrorCode.parameterError);
        }
        Date date = new Date();
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.BIND_COUPON_PHONE;
        couponParam.setApp_id(DiDiUrlConstant.didiAppId);
        couponParam.setSign(DiDiUrlConstant.didiSignPro);
        String timestamp = String.valueOf(date.getTime() / 1000);
        couponParam.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(couponParam, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = null;
        try {
            data = RetryUtil.retryRequestMethodUtil(signParameter, url, null, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {

        }
        DiDiRv diDiRv;
        try {
            diDiRv = JSONObject.parseObject(data, DiDiRv.class);
        } catch (Exception e) {
            throw DiDiException.create(EDiDiErrorCode.jsonConvertError);
        }
        return diDiRv;
    }
}
